package com.landis.temple.mobile;

import android.app.Activity;
import android.content.Intent;
import android.content.res.Resources;
import android.os.Bundle;
import android.util.Log;
import android.view.View;
import android.view.View.OnClickListener;
import android.widget.EditText;
import android.widget.TextView;

public class CreateActivity extends Activity implements OnClickListener
{
    private TwitterStoryDatabase tsdb;
    
    private int action; 
    private long author_id;
    private long story_id;
    
    public String[] returnedType = { "story_id" , "chapter_id" };
    
    /** Called when the activity is first created. */
    @Override
    public void onCreate(Bundle savedInstanceState) 
    {
        super.onCreate( savedInstanceState );
        setContentView( R.layout.create );
        
        action = getIntent().getExtras().getInt("action");
        author_id = getIntent().getExtras().getLong("author");

        switch( action )
        {
            case TwitterLibrary.CREATE_CHAPTER :
                findViewById(R.id.chapter_text).setVisibility(View.VISIBLE);
                ( (TextView) findViewById( R.id.create_title ) ).setText( R.string.create_chapter );
                
                story_id = getIntent().getExtras().getLong("story_id");
                
                break;
                
            case TwitterLibrary.CREATE_STORY :
                findViewById(R.id.title_panel).setVisibility(View.VISIBLE);
                ( (TextView) findViewById( R.id.create_title) ).setText( R.string.create_story );
                
                break;
        }
        
        findViewById(R.id.commit_button).setOnClickListener( this );
             
    }

    @Override
    public void onClick(View button) 
    {
        tsdb = new TwitterStoryDatabase(this.getApplicationContext());
        tsdb.open();   
        
        long result = -1;
        switch( action )
        {
            case TwitterLibrary.CREATE_CHAPTER :
                String text = ((EditText)findViewById(R.id.chapter_text)).getText().toString();
                
                Log.d("creating chapter","story_id is " + story_id + " and now creating chapter");
                result = tsdb.createChapter( story_id , author_id, text);                
                break;
                
            case TwitterLibrary.CREATE_STORY :
                String title = ((EditText)findViewById(R.id.title_text)).getText().toString();
                
                result = tsdb.createStory( author_id, title );
                break;
        }
        
        Intent i = new Intent();
        i.putExtra( returnedType[action] , result );
        
        finish();
    }
    
    @Override
    protected void onDestroy() 
    {
        super.onDestroy();
        
        if( tsdb != null )
        {
            tsdb.close();
        }
    }
}
